package org.yun.biz.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.yun.biz.dao.PrizeRepository;
import org.yun.biz.model.Prize;
import org.yun.biz.service.PrizeService;
import org.yun.constants.Constant;
import org.yun.constants.RedisConstant;
import org.yun.util.RedisUtil;
import org.yun.worker.ReplenishStock;

import javax.annotation.Resource;
import java.util.List;

import static org.yun.constants.Constant.PRIZE_UNIQUE;
import static org.yun.constants.RedisConstant.COUPON_LIST;
import static org.yun.constants.RedisConstant.PRIZE_ID;

/**
 * @author liyunfeng31
 */
@Slf4j
@Service
public class PrizeServiceImpl implements PrizeService {

    @Resource
    private PrizeRepository prizeDao;
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ReplenishStock replenishStock;


    @Override
    public void syncStockToCache() {
        List<Prize> prizeList = prizeDao.findAll();
        redisTemplate.executePipelined((RedisCallback<String>) connection -> {
            connection.openPipeline();
            prizeList.forEach(x -> {
                connection.set((PRIZE_ID + x.getPrizeId()).getBytes(), x.getValidStock().toString().getBytes());
            });
            return null;
        });
        prizeList.forEach(x->{
            if(x.getPrizeType().equals(PRIZE_UNIQUE)){
                Long prizeId = x.getPrizeId();
                Long couponNum = redisUtil.lLen(COUPON_LIST + prizeId);
                if(couponNum.intValue() == 0){
                    int count = replenishStock.doReplenishStock(prizeId, 1000);
                    log.info("奖品ID：{} 补货结果：{}", prizeId, count);
                }
            }
        });
    }
}
